package net.wangds.imagecomp.comp;

import net.wangds.common.base.space.Loc;
import net.wangds.common.base.space.Size;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * 图片组合工具.
 */
@Component
public class ImageCombineComp {


    /**
     * 将img图片绘制在bg图片的指定位置.
     * @param bg 背景图片.
     * @param img 要绘制的内容.
     * @param loc 位置.
     * @param size 大小.
     */
    public static void combine(BufferedImage bg, Image img, Loc<Integer> loc, Size<Integer> size){

        if(bg==null){
            return;
        }

        if(img==null){
            return;
        }

        int bg_width = bg.getWidth();
        int bg_height = bg.getHeight();

        int img_width = img.getWidth(null);
        int img_height = img.getHeight(null);

        int top = loc.getTop();
        int left = loc.getLeft();
        int width = size.getWidth();
        int height = size.getHeight();

        if(top<0){
            top = 0;
        }
        if(left<0){
            left = 0;
        }

        if(top>bg_height||left>bg_width){
            //在背景画布之外.
            return;
        }

        if(left+width>bg_width){
            width = bg_width-left;
        }
        if(top+height>bg_height){
            height = bg_height-top;
        }

        int t = top;
        int l = left;
        int w = width;
        int h = height;


        DrawOperate.draw(bg.getGraphics(), (g)->{
            //g.drawImage(img, t, l, w,h, null);
            g.drawImage(img,t,l,w,h,0,0,img_width,img_height,null);
        });

        bg.flush();

    }

}
